<?php

class MainController extends Controller
{
	public function actionIndex()
	{
		$this->render('index');
	}
        
        public function actionUpload()
        {
            if($_FILES['xml_file']['size'] == 0 && empty($_POST['site_name']))
            {
                $message = "ERROR!<br /> Enter Site Name;<br /> Select file;";
                $this->render('index',array('message'=>$message));
                Yii::app()->end();
            }
            elseif(empty($_POST['site_name']))
            {
                $message = "ERROR!<br /> Enter Site Name;";
                $this->render('index',array('message'=>$message));
                Yii::app()->end();
            }
            elseif($_FILES['xml_file']['size'] != 0 && $_FILES['xml_file']['error'] == 0)
            {
                $file_name = $_FILES['xml_file']['name'];
                $tmp = $_FILES['xml_file']['tmp_name'];
            
                $type = substr($file_name, -4);
                
                if($type == ".csv")
                {
                    $new_file_name = time().$type;
                    
                    $attach_file = "files/xml/$new_file_name";
                    move_uploaded_file($tmp, $attach_file);
                    
                    $link_to_csv = Yii::app()->params['base-url']."/".$attach_file;

                    $xml_data = $this->csvPars($link_to_csv);
//                    echo "<pre>".print_r($xml_data, TRUE)."</pre>";
//                    die();
                    $count = count($xml_data);
                    $g_count = $y_count = $s_count = 0;
                    
                    $site_name = Yii::app()->getRequest()->getPost('site_name');
                    $site = new Site();
                    if($site->findByAttributes(array('url'=>$site_name)) == NULL)
                    {
                        
                        $site->url = $site_name;
                        $site->save();
                    }
                    $site_id = $site->findByAttributes(array('url'=>$site_name))->id;
                    $pars_id = time();
                    $model = new Position();
                    $html = "<div id='results'>";
                    $html .= "<table>";
                    $html .= "<thead>";
                    $html .= "<tr>";
                    $html .= "<th>№</th>";
                    $html .= "<th>Search words</th>";
                    $html .= "<th class='center_td'>Google</th>";
                    $html .= "<th class='center_td'>Yandex</th>";
                    $html .= "</tr>";
                    $html .= "</thead>";
                    $html .= "<tbody>";
                    for($i = 1;$i < $count; ++$i)
                    {
                        if(empty($xml_data[$i][0]))
                            continue;
                        $model->site_id = $site_id;
                        $model->pars_id = $pars_id;
                        $search_words = $model->search_words = iconv('cp1251','utf-8',$xml_data[$i][1]);
                        $g_position = $model->g_position = $xml_data[$i][2];
                        $y_position = $model->y_position = $xml_data[$i][3];
                        $model->save();
                        $model->id = FALSE;
                        $model->isNewRecord = TRUE;

                        if($g_position <= 10 && $g_position != 0) ++$g_count;
                        if($y_position <= 10 && $y_position != 0) ++$y_count;
                        if(($g_position <= 10 && $g_position != 0) && ($y_position <=10 && $y_position != 0))
                        {
                            ++$s_count;
                        }
                        elseif (($g_position <= 10 && $g_position!= 0) || ($y_position <=10 && $y_position != 0))
                        {
                            ++$s_count;
                        }

                        $html .= "<tr>";
                        $html .= "<td>".$xml_data[$i][0]."</td>";
                        $html .= "<td>".$search_words."</td>";
                        $html .= "<td class='center_td'>".$g_position."</td>";
                        $html .= "<td class='center_td'>".$y_position."</td>";
                        $html .= "</tr>";
                        
                    }

                    $results = new Results();
                    
                    $results->pars_id = $pars_id;
                    $g_r = $results->g_result = $g_count/$count*100.;
                    $y_r = $results->y_result = $y_count/$count*100;
                    $s_r = $results->s_result = $s_count/$count*100;
                    
                    $results->save();
                    $html .= "<tr>";
                    $html .= "<td></td>";
                    $html .= "<td></td>";
                    $html .= "<td class='center_td'><b>".$g_count."</b></td>";
                    $html .= "<td class='center_td'><b>".$y_count."</b></td>";
                    $html .= "</tr>";
                    $html .= "<tr>";
                    $html .= "<td></td>";
                    $html .= "<td></td>";
                    $html .= "<td class='center_td'><b>".round($g_r,2)."%</b></td>";
                    $html .= "<td class='center_td'><b>".round($y_r,2)."%</b></td>";
                    $html .= "</tr>";
                    $html .= "<tr>";
                    $html .= "<td></td>";
                    $html .= "<td></td>";
                    $html .= "<td colspan=2><center><b>".round($s_r,2)."%</b></center></td>";
                    $html .= "</tr>";
                    $html .= "</tbody>";
                    $html .= "</table>";
                    $html .= "</div>";

                    $this->render('index', array('show_results'=>$html));
                }
                else
                {
                      $message = "ERROR is not CSV !";
                      $this->render('index',array('message'=>$message));
                }
                
               

            }
            else
            {
                $message = "ERROR Select file !";
                $this->render('index',array('message'=>$message));
            }
            
            
        }
        
        protected function csvPars($link_to_csv)
        {
            $csv_lines  = file($link_to_csv);
            if(is_array($csv_lines))
            {
                //разбор csv
                $cnt = count($csv_lines);
                for($i = 0; $i < $cnt; $i++)
                {
                $line = $csv_lines[$i];
                $line = trim($line);
                //указатель на то, что через цикл проходит первый символ столбца
                $first_char = true;
                //номер столбца
                $col_num = 0;
                $length = strlen($line);
                $skip_char = FALSE;
                $column = '';
                for($b = 0; $b < $length; $b++)
                {
                    //переменная $skip_char определяет обрабатывать ли данный символ
                    if($skip_char != true)
                    {
                    //определяет обрабатывать/не обрабатывать строку
                    ///print $line[$b];
                    $process = true;
                    //определяем маркер окончания столбца по первому символу
                    if($first_char == true)
                    {
                        if($line[$b] == '"')
                        {
                        $terminator = '";';
                        $process = false;
                        }
                        else
                        $terminator = ';';
                        $first_char = false;
                    }

                    //просматриваем парные кавычки, опредляем их природу
                    if($line[$b] == '"')
                    {
                        $next_char = $line[$b + 1];
                        //удвоенные кавычки
                        if($next_char == '"')
                        $skip_char = true;
                        //маркер конца столбца
                        elseif($next_char == ';')
                        {
                        if($terminator == '";')
                        {
                            $first_char = true;
                            $process = false;
                            $skip_char = true;
                        }
                        }
                    }

                    //определяем природу точки с запятой
                    if($process == true)
                    {
                        if($line[$b] == ';')
                        {
                        if($terminator == ';')
                        {

                            $first_char = true;
                            $process = false;
                        }
                        }
                    }

                    if($process == true)
                        $column .= $line[$b];

                    if($b == ($length - 1))
                    {
                        $first_char = true;
                    }

                    if($first_char == true)
                    {

                        $values[$i][$col_num] = $column;
                        $column = '';
                        $col_num++;
                    }
                    }
                    else
                    $skip_char = false;
                }
                }
            }
            
            return $values;
        }
        
        public function actionDownload()
        {
            // получение переменных, если нет - остановка сценария
            if(empty($_POST['filename']) || empty($_POST['content'])){
                    exit;
            }

            // получаем корректное имя файла
            $filename = preg_replace('/[^a-z0-9-\_.]/i','',$_POST['filename']);

            // отправка заголовков браузеру
            header("Cache-Control: ");
            header("Content-type: text/plain"); // говорим что выдаем текст
            header('Content-Disposition: attachment; filename="'.$filename.'"'); // имя для сохраняемого файла
            echo "<html>";
            echo "<head>";
            echo "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />";
            echo "</head>";
            echo "<body>";
            echo $_POST['content'];
            echo "</body>";
            echo "</html>";
        }
        
}